<template>
    <view class="pages" :class="GlobalThemes.commonBackGroundClass">
        <view class="search-top-box" id="navbar">
            <u-navbar
                back-icon-color="#ffffff"
                :is-back="true"
                :border-bottom="false"
                :background="typelist[tabIndex].background"
            >
                <view class="mp-name">
                    <text>{{ i18n('index').appName }}</text>
                </view>
            </u-navbar>
        </view>
        <view class="content-box">
            <!-- #ifdef MP-WEIXIN -->
            <view v-if="!isShowxx" class="cu-bar" @click="openPicModel">
                <view class="action fl nav-arrow">
                    <u-icon
                        name="pushpin"
                        label="小窗模式"
                        label-size="30"
                        size="36"
                    ></u-icon>
                </view>
                <view class="fr">
                    <text class="text-grey text-sm video-more-text">
                        {{ isOpen ? '已开启' : '已关闭' }}
                    </text>
                </view>
            </view>
            <!-- #endif -->
            <view class="cu-bar" @click="clearHistoryCache">
                <view class="action fl nav-arrow">
                    <u-icon
                        name="close-circle"
                        :label="i18n('setting').clearHistory"
                        label-size="30"
                        size="36"
                    ></u-icon>
                </view>
            </view>
            <view class="cu-bar" @click="clearCache">
                <view class="action fl nav-arrow">
                    <u-icon
                        name="info-circle"
                        :label="i18n('setting').clearCache"
                        label-size="30"
                        size="36"
                    ></u-icon>
                </view>
                <view class="fr">
                    <text class="text-grey text-sm video-more-text">
                        {{ cacheSize }}
                    </text>
                </view>
            </view>
            <view class="cu-bar" @click="changeLang">
                <view class="action fl nav-arrow">
                    <u-icon
                        name="setting"
                        :label="i18n('setting').changeLang"
                        label-size="30"
                        size="36"
                    ></u-icon>
                </view>
            </view>
            <!-- #ifdef MP-WEIXIN -->
            <view class="cu-bar bg-my-gray solid-bottom" @click="updateWxMpVer">
                <view class="action fl nav-arrow">
                    <u-icon
                        name="level"
                        :label="i18n('setting').version"
                        label-size="30"
                        size="36"
                    ></u-icon>
                </view>
            </view>
            <!-- #endif -->
            <!-- #ifdef APP-PLUS -->
            <view class="cu-bar bg-my-gray solid-bottom" @click="updateVer">
                <view class="action fl nav-arrow">
                    <u-icon
                        name="level"
                        :label="i18n('setting').version"
                        label-size="30"
                        size="36"
                    ></u-icon>
                </view>
                <view class="fr">
                    <text class="text-grey text-sm video-more-text">
                        {{ version }}
                    </text>
                </view>
            </view>
            <!-- #endif -->
        </view>
        <!-- #ifdef MP-WEIXIN -->
        <!-- 广告 -->
        <Adview
            v-if="adSwitchKg"
            :adSwitchKg="adSwitchKg"
            :homeADList="oneAd"
        ></Adview>
        <!-- #endif -->
        <view class="padding flex flex-direction bottom-login-btn" v-if="login">
            <u-button type="info" @click="logout">
                {{ i18n('setting').logout }}
            </u-button>
        </view>
    </view>
</template>

<script>
const MyApp = getApp();
const globalData = MyApp.globalData;
import Adview from '@/components/home-ad/ad-view.vue';
export default {
    components: {
        Adview
    },
    data() {
        return {
            adSwitchKg:
                globalData.adSwitchKg ||
                uni.getStorageSync('sys_config').ad_switch,
            oneAd: MyApp.getOneAd('alert_public'),
            tabIndex: 0,
            typelist: globalData.typelist,
            version: '1.0.0',
            login: true,
            downloadTask: null,
            cacheSize: 0,
            homeADList: null,
            isShowxx: globalData.centerShowxx,
            isOpen: uni.getStorageSync('pictureModel') || 0
        };
    },
    computed: {
        i18n() {
            return globalData.$t;
        }
    },
    methods: {
        openPicModel() {
            let _this = this;
            uni.showModal({
                title: '提示',
                content: _this.isOpen
                    ? '是否关闭小窗模式？'
                    : '播放中的视频在退出播放页后将以小窗模式继续播放，是否开启？',
                success(res) {
                    if (res.confirm) {
                        _this.isOpen = _this.isOpen ? 0 : 1;
                        uni.setStorageSync('pictureModel', _this.isOpen);
                    }
                }
            });
        },
        logout() {
            let _this = this;
            _this.$http
                .post('/user/auth/logout', {})
                .then(res => {
                    uni.showToast({ title: res.msg, icon: 'none' });
                    if (res.code == 200) {
                        // uni.removeStorageSync('userInfo');
                        uni.setStorageSync('userInfo', null);
                        uni.switchTab({
                            url: '/pages/user/index'
                        });
                    }
                })
                .catch(err => {});
        },
        changeLang() {
            MyApp.changeLang();
        },
        init() {
            let userinfo = uni.getStorageSync('userInfo');
            if (!userinfo) {
                this.login = false;
            }
            // #ifdef APP-PLUS
            this.version = plus.runtime.version;
            this.cacheSize = this.showCache();
            // #endif
            // #ifndef APP-PLUS
            this.cacheSize = this.get_cache_size();
            // #endif
        },
        updateWxMpVer() {
            MyApp.checkWxmpUpdate(true);
        },
        updateVer() {
            this.checkUpdate();
        },
        checkUpdate() {
            var _this = this;
            _this.$http
                .post('/videos/config/updateInfo', {})
                .then(res => {
                    if (res.code == 200) {
                        let versionInfo = res.data;
                        let io = plus.os.name.toLowerCase();
                        switch (io) {
                            case 'android':
                                _this.AndroidCheckUpdate(versionInfo.android);
                                break;
                            default:
                                return;
                        }
                    }
                })
                .catch(err => {
                    
                });
        },
        AndroidCheckUpdate(versionInfo) {
            let _this = this;
            let ver = plus.runtime.version.split('.').join('');
            if (
                versionInfo.version.split('.').join('') > ver &&
                versionInfo.atOnce == true
            ) {
                uni.showModal({
                    title: '更新提醒',
                    content:
                        '有新的版本发布：' +
                        versionInfo.version +
                        '\n当前版本：' +
                        plus.runtime.version +
                        '\n是否立即下载更新？',
                    success: function(res) {
                        if (res.confirm) {
                            _this.downLoad(versionInfo);
                        } else {
                            return false;
                        }
                    }
                });
            } else {
                uni.showToast({
                    title: '当前为最新版本',
                    icon: 'none'
                });
            }
        },
        downLoad(versionInfo) {
            var _this = this;
            var w = plus.nativeUI.showWaiting('　　 开始下载...　　 ');
            _this.downloadTask = plus.downloader.createDownload(
                versionInfo.download_url,
                {}
            );
            _this.downloadTask.start();
            // 进度条
            _this.downloadTask.addEventListener('statechanged', function(
                task,
                status
            ) {
                switch (task.state) {
                    case 1: // 开始
                        w.setTitle('　　 准备下载...　　 ');
                        break;
                    case 2: // 已连接到服务器
                        w.setTitle('　　 已连接到服务器...　　 ');
                        break;
                    case 3:
                        var a = (task.downloadedSize / task.totalSize) * 100;
                        w.setTitle('　　 已下载' + parseInt(a) + '%　　 ');
                        break;
                    case 4: // 下载完成
                        w.close();
                        uni.showModal({
                            title: '下载完成',
                            content: '是否立即安装？',
                            success: function(res) {
                                if (res.confirm) {
                                    _this.installApp();
                                } else {
                                    return false;
                                }
                            }
                        });
                        break;
                }
            });
        },
        installApp() {
            var _this = this;
            if (_this.downloadTask.state == 4) {
                plus.runtime.install(
                    plus.io.convertLocalFileSystemURL(
                        _this.downloadTask.filename
                    ),
                    {},
                    function() {},
                    function(error) {
                        uni.showToast({
                            title: '安装失败',
                            mask: false,
                            duration: 1500
                        });
                    }
                );
            } else {
                uni.showToast({
                    title: '更新失败',
                    mask: false,
                    duration: 1500
                });
            }
        },
        clearHistoryCache() {
            uni.showModal({
                title: '提示',
                content: '是否要清除历史记录',
                success: function(res) {
                    if (res.confirm) {
                        uni.setStorageSync('historyList', []);
                    }
                }
            });
        },
        clearCache() {
            let _this = this,
                con = '';
            // #ifdef APP-PLUS
            con = '是否清除所有缓存（包括下载的视频及所有数据缓存）？';
            // #endif
            // #ifndef APP-PLUS
            con =
                '是否清除所有数据缓存（包括登录状态、浏览历史等）？若出现“未找到此影片信息”的提示，可尝试此操作';
            // #endif
            uni.showModal({
                title: '清除缓存',
                content: con,
                success: function(res) {
                    if (res.confirm) {
                        // #ifdef APP-PLUS
                        _this.removeAllDownload();
                        // #endif
                        _this.removeLocalStorage();
                    } else {
                        return false;
                    }
                }
            });
        },
        removeLocalStorage() {
            let _this = this;
            uni.clearStorage();
            setTimeout(function() {
                _this.cacheSize = _this.get_cache_size();
                uni.switchTab({
                    url: '/pages/user/index'
                });
            }, 500);
        },
        removeAllDownload() {
            // #ifdef APP-PLUS
            let _this = this;
            plus.io.resolveLocalFileSystemURL(
                '_downloads/',
                function(entry) {
                    entry.removeRecursively(
                        function(entry) {
                            //递归删除其下的所有文件及子目录
                            uni.showToast({
                                title: '缓存清理完成',
                                icon: 'none'
                            });
                        },
                        function(e) {
                            uni.showToast({
                                title: e.message,
                                icon: 'none'
                            });
                        }
                    );
                    setTimeout(function() {
                        _this.showCache();
                    }, 500);
                },
                function(e) {
                    uni.showToast({
                        title: '文件路径读取失败',
                        icon: 'none'
                    });
                }
            );
            // #endif
        },
        get_cache_size() {
            var obj = '';
            obj = uni.getStorageInfoSync().keys;
            if (obj !== '') {
                var size = 0;
                obj.forEach(v => {
                    let item = uni.getStorageSync(v);
                    if (item) {
                        if (typeof item == 'object') {
                            size += JSON.stringify(item).length;
                        }
                        if (typeof item == 'number') {
                            size += item.toString().length;
                        }
                        if (typeof item == 'string') {
                            size += item.length;
                        }
                    }
                });
                return (size / 1024).toFixed(2) + 'KB';
            }
            return '0KB';
        },
        showCache() {
            let _this = this;
            plus.io.resolveLocalFileSystemURL(
                '_downloads/',
                function(entry) {
                    //通过URL参数获取目录对象或文件对象
                    var fileSize = 0;
                    var directoryReader = entry.createReader();
                    directoryReader.readEntries(
                        function(entries) {
                            //获取当前目录中的所有文件和子目录
                            for (var i = 0; i < entries.length; i++) {
                                if (entries[i].isFile) {
                                    entries[i].file(
                                        function(file) {
                                            fileSize += file.size * 0.0009766;
                                        },
                                        function(e) {
                                            uni.showToast({
                                                title: e.message,
                                                icon: 'none'
                                            });
                                        }
                                    );
                                } else {
                                    entries[i].getMetadata(
                                        function(metadata) {
                                            fileSize +=
                                                metadata.size * 0.0009766; //1字节=0.0009766kb
                                        },
                                        function() {
                                            uni.showToast({
                                                title: e.message,
                                                icon: 'none'
                                            });
                                        }
                                    );
                                }
                            }
                        },
                        function(e) {
                            uni.showToast({
                                title: '文件读取失败',
                                icon: 'none'
                            });
                        }
                    );
                    fileSize = _this.get_cache_size();
                    setTimeout(function() {
                        if (Math.ceil(fileSize) > 1024) {
                            _this.cacheSize =
                                _this.fomatFloat(
                                    Math.ceil(fileSize) / 1024,
                                    2
                                ) +
                                parseFloat(fileSize) +
                                'M';
                        } else {
                            _this.cacheSize =
                                _this.fomatFloat(Math.ceil(fileSize), 2) +
                                parseFloat(fileSize) +
                                'Kb';
                        }
                    }, 500);
                },
                function(e) {
                    uni.showToast({
                        title: '文件路径读取失败',
                        icon: 'none'
                    });
                }
            );
        },
        fomatFloat(num, n) {
            var f = parseFloat(num);
            if (isNaN(f)) {
                return false;
            }
            f = Math.round(num * Math.pow(10, n)) / Math.pow(10, n); // n 幂
            var s = f.toString();
            var rs = s.indexOf('.');
            //判定如果是整数，增加小数点再补0
            if (rs < 0) {
                rs = s.length;
                s += '.';
            }
            while (s.length <= rs + n) {
                s += '0';
            }
            return s;
        }
    },
    onLoad() {
        this.init();
    }
};
</script>

<style>
.content-box {
    padding: 10upx 30upx;
}
.bottom-login-btn {
    bottom: 0;
    position: fixed;
    width: 750rpx;
}
.cu-bar .action {
    margin-left: 0 !important;
}
</style>
